package com.mid;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Lxk on 2019/8/17.
 */
public class Solution105 {

    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if (preorder == null || inorder == null
                || preorder.length == 0 || inorder.length == 0) {
            return null;
        }
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return preIn(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1, map);
    }

    /**
     * 构造树结构
     *
     * @param p   先序序列
     * @param pi  先序中处理范围左边界（包含）
     * @param pj  先序中处理范围右边界（包含）
     * @param n   中序序列
     * @param ni  中序中处理范围左边界（包含）
     * @param nj  中序中处理范围右边界（包含）
     * @param map
     * @return
     */
    private TreeNode preIn(int[] p, int pi, int pj, int[] n, int ni, int nj, Map<Integer, Integer> map) {
        if (pi > pj) {
            return null;
        }
        TreeNode head = new TreeNode(p[pi]);
        int index = map.get(p[pi]);
        head.left = preIn(p, pi + 1, pi + index - ni, n, ni, index - 1, map);
        head.right = preIn(p, pi + index - ni + 1, pj, n, index + 1, nj, map);
        return head;
    }

    public static void main(String[] args) {
        int[] arrPre = {3, 9, 20, 15, 7};
        int[] arrIn = {9, 3, 15, 20, 7};
        Solution105 solution105 = new Solution105();
        TreeNode head = solution105.buildTree(arrPre, arrIn);
    }

}
